#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <thread>
#include <atomic>

#define PORT 8080 // 端口号

std::atomic<bool> isControlled(false);

void receiveCommands(int sock) {
    char buffer[1024] = {0};
    while (true) {
        // 接收控制命令
        int bytesReceived = read(sock, buffer, sizeof(buffer));
        if (bytesReceived > 0) {
            std::string command(buffer, bytesReceived);
            if (command == "控制") {
                isControlled = true;
                std::cout << "收到教师控制命令。\n";
            }
        }
    }
}

void userInput() {
    std::string input;
    while (true) {
        std::getline(std::cin, input);  // 接收用户输入
        if (input == "脱控") {
            isControlled = false;
            std::cout << "已解除教师控制。\n";

        }
    }
}

int main() {
    int sock = 0;
    struct sockaddr_in serv_addr;

    // 创建 socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        std::cerr << "Socket creation error\n";
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // 将IPv4地址从文本转换为二进制
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        std::cerr << "Invalid address/ Address not supported\n";
        return -1;
    }

    // 连接教师端
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        std::cerr << "Connection Failed\n";
        return -1;
    }

    std::thread receiver(receiveCommands, sock);
    receiver.detach(); 

    userInput();


    close(sock);
    return 0;
}

